import io, re
p = r'static/js/admin.js'
s = io.open(p, 'r', encoding='utf-8').read()
orig = s
# 1) Extend jsonModal state
s = re.sub(r"jsonModal:\s*\{[^}]*\}",
           "jsonModal: { visible: false, title: \"\", pretty: \"\", records: [], index: 0, total: 0 }",
           s, count=1)
# 2) Remove any inline alert fallback
s = s.replace("window.alert(this.jsonModal.pretty);", "")
# 3) Replace openOrderJson body
s = re.sub(r"openOrderJson\s*\([^)]*\)\s*\{[\s\S]*?\n\s*\},",
           (
            "openOrderJson(order) {\n"
            "      try {\n"
            "        const recs = (this.ordersRaw && this.ordersRaw.recordList) ? this.ordersRaw.recordList : [];\n"
            "        const idx = recs.findIndex(r => String(r.code || r.id) === String(order.code || order.id));\n"
            "        const title = 'Order JSON - ' + (order && order.code ? order.code : '');\n"
            "        this.openJsonFromRecords(recs, idx >= 0 ? idx : 0, title);\n"
            "      } catch (e) {\n"
            "        this.openJsonFromRecords([], 0, 'Order JSON');\n"
            "      }\n"
            "    },"
           ), s, count=1)
# 4) Replace openInventoryJson body
s = re.sub(r"openInventoryJson\s*\([^)]*\)\s*\{[\s\S]*?\n\s*\},",
           (
            "openInventoryJson(item) {\n"
            "      try {\n"
            "        const recs = Array.isArray(this.inventoryRaw) ? this.inventoryRaw : [];\n"
            "        const mc = String(item.materialCode || '');\n"
            "        const idx = recs.findIndex(r => String(r.material_code || r.product_code || r.productsku_code) === mc);\n"
            "        const title = 'Inventory JSON - ' + mc;\n"
            "        this.openJsonFromRecords(recs, idx >= 0 ? idx : 0, title);\n"
            "      } catch (e) {\n"
            "        this.openJsonFromRecords([], 0, 'Inventory JSON');\n"
            "      }\n"
            "    },"
           ), s, count=1)
# 5) Insert helper methods before mounted()
helpers = (
    "    openJsonFromRecords(records, index, title) {\n"
    "      this.jsonModal.records = Array.isArray(records) ? records : [];\n"
    "      this.jsonModal.total = this.jsonModal.records.length;\n"
    "      this.showJsonAt(index || 0);\n"
    "      this.jsonModal.title = title || 'JSON';\n"
    "      this.jsonModal.visible = true;\n"
    "    },\n"
    "    showJsonAt(i) {\n"
    "      if (!this.jsonModal.total) {\n"
    "        this.jsonModal.index = 0;\n"
    "        this.jsonModal.pretty = '[]';\n"
    "        return;\n"
    "      }\n"
    "      const n = this.jsonModal.total;\n"
    "      const idx = ((i % n) + n) % n;\n"
    "      this.jsonModal.index = idx;\n"
    "      const payload = this.jsonModal.records[idx];\n"
    "      try { this.jsonModal.pretty = JSON.stringify(payload, null, 2); } catch (e) { this.jsonModal.pretty = String(payload); }\n"
    "    },\n"
    "    nextJson() { this.showJsonAt((this.jsonModal.index || 0) + 1); },\n"
    "    prevJson() { this.showJsonAt((this.jsonModal.index || 0) - 1); },\n"
)
s = re.sub(r"\n\s*mounted\(\)\s*\{",
           "\n" + helpers + "  mounted() {",
           s, count=1)
# 6) Unify modal overlay: remove section-local overlays and add one global at end of template
mt = re.search(r"template:\s*`([\s\S]*?)`", s)
if mt:
    tpl = mt.group(1)
    # strip any existing modal blocks
    tpl2 = re.sub(r"<div v-if=\\\"jsonModal.visible\\\"[\s\S]*?</div>\s*</div>", "", tpl)
    # Add global overlay at end of template before closing
    overlay = (
        "\n      <!-- JSON Modal (global) -->\n"
        "      <div v-if=\"jsonModal.visible\" class=\"modal-mask\" style=\"position:fixed;left:0;top:0;right:0;bottom:0;background:rgba(0,0,0,0.35);display:flex;align-items:center;justify-content:center;z-index:9999;\">\n"
        "        <div class=\"modal\" style=\"background:#fff;border-radius:8px;min-width:60vw;max-width:80vw;max-height:80vh;display:flex;flex-direction:column;box-shadow:0 8px 24px rgba(0,0,0,0.2);\">\n"
        "          <div style=\"display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #eee;\">\n"
        "            <div>\n"
        "              <strong>{{ jsonModal.title }}</strong>\n"
        "              <span v-if=\"jsonModal.total\" style=\"margin-left:8px;color:#666;\">{{ jsonModal.index + 1 }} / {{ jsonModal.total }}</span>\n"
        "            </div>\n"
        "            <div>\n"
        "              <button class=\"btn\" type=\"button\" @click=\"prevJson\">上一条</button>\n"
        "              <button class=\"btn\" type=\"button\" @click=\"nextJson\" style=\"margin-left:6px;\">下一条</button>\n"
        "              <button class=\"btn\" type=\"button\" @click=\"closeJsonModal\" style=\"margin-left:6px;\">关闭</button>\n"
        "            </div>\n"
        "          </div>\n"
        "          <div style=\"padding:12px;overflow:auto;\">\n"
        "            <pre style=\"margin:0;white-space:pre-wrap;word-break:break-all;\">{{ jsonModal.pretty }}</pre>\n"
        "          </div>\n"
        "        </div>\n"
        "      </div>\n"
    )
    tpl2 = tpl2.rstrip() + "\n" + overlay + "\n"
    s = s[:mt.start(1)] + tpl2 + s[mt.end(1):]

if s != orig:
    io.open(p, 'w', encoding='utf-8', newline='\n').write(s)
    print('UPDATED')
else:
    print('NOCHANGE')
